﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace TwoStageLock.ViewModels;

[ObservableObject]
public partial class MainPageViewModel {
    private volatile bool _hasBackground = false;

    private volatile object _backgroundLock = new object();

    [ObservableProperty] private string _backgroundUrl;

    private List<string> _urls =
        Enumerable.Range(0, 3).Select(p => p.ToString()).ToList();

    [RelayCommand]
    private void SetBackground() {
        var threads = Enumerable.Range(0, 3).Select(p => new Thread(() => {
            var random = new Random();
            Thread.Sleep(random.Next(1000));

            if (_hasBackground) {
                return;
            }

            var url = _urls[p];
            // Download url
            Thread.Sleep(random.Next(5));
            BackgroundUrl = url;
            _hasBackground = true;
        }));

        foreach (var thread in threads) {
            thread.Start();
        }
    }
}